package com.example.filelock.fragment;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ExpandableListActivity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.provider.DocumentsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnticipateInterpolator;
import android.view.animation.BounceInterpolator;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.filelock.R;
import com.example.filelock.entity.FileViewEntity;
import com.example.filelock.utils.BasDataUtil;
import com.example.filelock.utils.FileUtil;
import com.example.filelock.utils.LoadingFile;
import com.example.filelock.utils.LogOnFileItem;
import com.example.filelock.utils.PageViewUitl;
import com.rey.material.app.BottomSheetDialog;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DecryptionFragment extends Fragment {
    private View view;
    public static SwipeRefreshLayout mDecryptionLayoutRefresh;
    private ListView mDecryptionLvFileList;
    private ImageView mDecryptionIvAdd;
    private String returnPath;
    public static List<FileViewEntity> fileViewEntities;
    public static FileLayoutViewAdapter fileLayoutViewAdapter;
    private RelativeLayout mDecryptionLayoutWarning;
    private ImageView mDecryptionIvError;
    private ImageView mDecryptionIvAdd3;
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;
    private boolean isAddIconAlp = false;
    private Map<String, List<FileViewEntity>> selectFile3sChild;
    private Map<Integer, String> selectFile3sGroup;
    private SelectFile3Adapter selectFile3Adapter;
    private BottomSheetDialog bottomSheetDialog;
    private int DE_MSG_DELETE_OK = 0x05;

    @Override
    public void onResume() {
        //判定是否显示警告
        mDecryptionLayoutWarning.setVisibility(sp.getBoolean(BasDataUtil.SP_IsWarning, true) ? View.VISIBLE : View.GONE);
        updateFileView(getContext());//刷新listView
        super.onResume();
    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == DE_MSG_DELETE_OK) {
                init3Data();
                Toast.makeText(getContext(), "删除成功", Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.activity_decryption_fragment, container, false);
        initView();
        setView();
        return view;
    }


    //初始化数据
    private void init3Data() {
        try {
            selectFile3sGroup = new HashMap<>();
            selectFile3sChild = new HashMap<>();
            selectFile3sGroup.put(0, "QQ");
            selectFile3sGroup.put(1, "微信");
            selectFile3sGroup.put(2, "TIM");
            //qq发送路径
            boolean isLookFile = true;
            for (int key: selectFile3sGroup.keySet()) {
                isLookFile =  putFile3sData(selectFile3sGroup.get(key),key);
            }
            if (!isLookFile)
                Toast.makeText(getContext(), "没有找到文件，或设备文件位置不一致!", Toast.LENGTH_SHORT).show();

            selectFile3Adapter.notifyDataSetChanged();
        } catch (Exception e) {
            Log.d(BasDataUtil.LOG_TOAST, "解密页面刷新第三方文件错误:" + e.toString());
        }
    }
    private boolean putFile3sData(String mode,int index){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        fileViewEntities = new ArrayList<>();
        File file = new File(BasDataUtil.getSelect3FilePath(mode));
        if (file.exists()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (!files[i].isDirectory()) {
                    FileViewEntity fileViewEntity = new FileViewEntity();
                    fileViewEntity.setFileEnd(FileUtil.getFileNameEnd(files[i].getName()));
                    fileViewEntity.setFileName(files[i].getName());
                    fileViewEntity.setFilePath(files[i].getPath());
                    fileViewEntity.setFileMsg(String.format("%.2f", (double) files[i].length() / 1000000) + "m | " + dateFormat.format(files[i].lastModified()));
                    fileViewEntities.add(fileViewEntity);
                }
            }
        } else return false;
        selectFile3sChild.put(selectFile3sGroup.get(index), fileViewEntities);
        return  true;
    }

    private void setView() {
//        点击自定义选择文件
        mDecryptionIvAdd3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                首先刷新文件
                init3Data();
                View logView = LayoutInflater.from(getContext()).inflate(R.layout.de_log_custom_select_file, null);
                ExpandableListView elv_list = logView.findViewById(R.id.deLog_elv_selectFile);
                elv_list.setAdapter(selectFile3Adapter);
                bottomSheetDialog = new BottomSheetDialog(getContext());
                bottomSheetDialog.contentView(logView)          //获取键时用了view那么此时一点要用view否则就获取不到点击事件
                        .inDuration(100)
                        .outDuration(100)
                        .cancelable(true)
                        .show();
            }
        });
//        点击系统选择文件
        mDecryptionIvAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击选择文件
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");//无类型限制
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent, 1);
            }
        });
//       长按透明
        mDecryptionIvAdd.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                isAddIconAlp = !isAddIconAlp;
                mDecryptionIvAdd.setAlpha(isAddIconAlp ? (float) 0.2 : 1);
                return true;
            }
        });
        mDecryptionLayoutRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                updateFileView(getContext());
            }
        });
//        点击消失警告
        mDecryptionIvError.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //消失警告
                editor.putBoolean(BasDataUtil.SP_IsWarning, false);
                editor.commit();
                mDecryptionLayoutWarning.setVisibility(View.GONE);
            }
        });
        mDecryptionLvFileList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    LogOnFileItem logOnFileItem = new LogOnFileItem(getContext());
                    logOnFileItem.onItemFileSet(fileViewEntities.get(position), false);
                    logOnFileItem.addLogCompete(new LogOnFileItem.LogCompete() {
                        @Override
                        public void onDeleteCompete() {
                            updateFileView(getContext());
                            Toast.makeText(getContext(), "删除成功", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onLoadingOkCompete() {

                        }
                    });
                } catch (Exception e) {

                }

            }
        });
    }


    public static void updateFileView(Context context) {
        try {
            //获取文件里所有文件
            fileViewEntities = new ArrayList<>();
            String path = BasDataUtil.getDecryptionPath();
            File file = new File(path);
            File[] files = file.listFiles();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            for (int i = 0; i < files.length; i++) {
                FileViewEntity fileViewEntity = new FileViewEntity();
                fileViewEntity.setFileName(files[i].getName());
                fileViewEntity.setFileEnd(FileUtil.getFileNameEnd(files[i].getName()));
                fileViewEntity.setFileMsg(String.format("%.2f", (double) files[i].length() / 1000000) + "m | " + dateFormat.format(files[i].lastModified()));
                fileViewEntity.setFilePath(files[i].getPath());
                fileViewEntities.add(fileViewEntity);
            }
            fileLayoutViewAdapter.notifyDataSetChanged();
            mDecryptionLayoutRefresh.setRefreshing(false);
        } catch (Exception e) {
            Log.d(BasDataUtil.LOG_TOAST, "解密页刷新错误:" + e.toString());
            //        初始化文件夹
            FileUtil.initMainFile(context);
            mDecryptionLayoutRefresh.setRefreshing(false);
        }
    }
    //    选择文件的回调

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        try {
            if (resultCode == Activity.RESULT_OK) {
                returnPath = "";
                Uri uri = data.getData();
                if ("file".equalsIgnoreCase(uri.getScheme())) {//使用第三方应用打开
                    returnPath = uri.getPath();
                    return;
                }
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {//4.4以后
                    returnPath = FileUtil.getPath(getContext(), uri);

                } else {//4.4以下下系统调用方法
                    returnPath = FileUtil.getRealPathFromURI(uri);
                }
                if (returnPath != null && !returnPath.equals("")) {
                    setPwdLog(returnPath);
                }
            }
        } catch (Exception e) {
            Log.d(BasDataUtil.LOG_TOAST, "解密页面回调文件错误:" + e.toString());
        }

    }

    private void setPwdLog(final String redPath) {
        final View logView = LayoutInflater.from(getContext()).inflate(R.layout.log_decryption_view, null);
        final EditText ev_pwd = logView.findViewById(R.id.log_encryption_et_pwd);
        AlertDialog alertDialog = new AlertDialog.Builder(getContext())
                .setTitle("解密文件")
                .setView(logView)
                .setNegativeButton("取消", null)
                .setPositiveButton("解密", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            //点击加密，获取组件
                            //弹出加载对话框
                            final String path = redPath;
                            String s_pwd = ev_pwd.getText().toString();
                            if (s_pwd.equals("")) {
                                Toast.makeText(getContext(), "不能为空!", Toast.LENGTH_SHORT).show();
                            } else if (s_pwd.length() < 3 || s_pwd.length() > 6) {
                                Toast.makeText(getContext(), "密码长度不符合!", Toast.LENGTH_SHORT).show();
                            } else {
                                File file = new File(redPath);
                                LoadingFile loadingFile = new LoadingFile(getContext(), file.length());
                                if (!loadingFile.decryptionFile(redPath, s_pwd)) {
                                    Toast.makeText(getContext(), "文件为空", Toast.LENGTH_SHORT).show();
                                }
                                loadingFile.addLoadingOk(new LoadingFile.LoadingFileOk() {
                                    @Override
                                    public void onLoadingOk() {
                                        if (bottomSheetDialog != null) {
                                            bottomSheetDialog.cancel();
                                            Toast.makeText(getContext(), "解密成功!", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });
                            }
                        } catch (Exception e) {
                            Log.d(BasDataUtil.LOG_TOAST, "解密页面填写密码错误：" + e.toString());
                        }


                    }
                })
                .show();
    }

    private void initView() {
        mDecryptionIvAdd = view.findViewById(R.id.decryption_iv_add);
        mDecryptionLayoutRefresh = view.findViewById(R.id.decryption_layout_refresh);
        mDecryptionLvFileList = view.findViewById(R.id.decryption_lv_fileList);
        mDecryptionLayoutWarning = view.findViewById(R.id.decryption_layout_warning);
        mDecryptionIvError = view.findViewById(R.id.decryption_iv_error);
        mDecryptionIvAdd3 = view.findViewById(R.id.decryption_iv_add3);
        mDecryptionLayoutRefresh.setColorSchemeColors(getResources().getColor(R.color.mainColor));
        //        适配listview和swipeRefreshLayout
        PageViewUitl.adapterLS(mDecryptionLvFileList, mDecryptionLayoutRefresh);
        fileViewEntities = new ArrayList<>();
        fileLayoutViewAdapter = new FileLayoutViewAdapter();
        mDecryptionLvFileList.setAdapter(fileLayoutViewAdapter);
        fileLayoutViewAdapter.notifyDataSetChanged();
        sp = getContext().getSharedPreferences(BasDataUtil.SP_MAIN, Context.MODE_PRIVATE);
        editor = sp.edit();
        selectFile3sChild = new HashMap<>();
        selectFile3sGroup = new HashMap<>();
        selectFile3Adapter = new SelectFile3Adapter();
    }

    //    适配器
    public class FileLayoutViewAdapter extends BaseAdapter {


        @Override
        public int getCount() {
            return fileViewEntities.size();
        }

        @Override
        public FileViewEntity getItem(int position) {
            return fileViewEntities.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.file_layout_view, null);
                convertView.setTag(new ViewHolder(convertView));
            }
            initializeViews((FileViewEntity) getItem(position), (ViewHolder) convertView.getTag());
            return convertView;
        }

        private void initializeViews(final FileViewEntity object, ViewHolder holder) {
            //TODO implement
            holder.fileViewTvFileName.setText(object.getFileName());
            holder.fileViewTvMsg.setText(object.getFileMsg());
            if (object.getFileEnd() != null) {
                int i = getContext().getResources().getIdentifier(getContext().getPackageName() + ":drawable/file_icon_" + FileUtil.getFileNameEedQ(object.getFileEnd()),
                        null, null);
                if (i == 0)
                    holder.fileViewImg.setImageResource(R.drawable.file_icon_default);
                else
                    holder.fileViewImg.setImageResource(i);
            }
        }

        protected class ViewHolder {
            private TextView fileViewTvFileName;
            private TextView fileViewTvMsg;
            private CheckBox fileViewRBtSelect;
            private ImageView fileViewImg;

            public ViewHolder(View view) {
                fileViewTvFileName = (TextView) view.findViewById(R.id.fileView_tv_fileName);
                fileViewTvMsg = (TextView) view.findViewById(R.id.fileView_tv_msg);
                fileViewRBtSelect = view.findViewById(R.id.fileView_cbt_select);
                fileViewImg = view.findViewById(R.id.fileView_iv_img);
            }
        }
    }

    //    三方选择适配器
    public class SelectFile3Adapter extends BaseExpandableListAdapter {

        @Override
        public int getGroupCount() {
            return selectFile3sGroup.size();
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            List<FileViewEntity> list = selectFile3sChild.get(selectFile3sGroup.get(groupPosition));
            return list != null ? list.size() : 0;
        }

        @Override
        public Object getGroup(int groupPosition) {
            return selectFile3sGroup.get(groupPosition);
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return selectFile3sChild.get(selectFile3sGroup.get(groupPosition)).get(childPosition);
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            try {
                final GroupViewHolder holder;
                if (convertView == null) {
                    holder = new GroupViewHolder();
                    convertView = LayoutInflater.from(getContext()).inflate(R.layout.de_log_custom_view_child, null);
                    holder.tvTitle = convertView.findViewById(R.id.deLogChild_tv);
                    holder.tvDelete = convertView.findViewById(R.id.deLogChild_tv_delete);
                    convertView.setTag(holder);
                } else {
                    holder = (GroupViewHolder) convertView.getTag();
                }
                holder.tvTitle.setText(selectFile3sGroup.get(groupPosition)+"-File");
                holder.tvDelete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String title = selectFile3sGroup.get(groupPosition);
                        AlertDialog alertDialog = new AlertDialog.Builder(getContext())
                                .setTitle("提示:")
                                .setMessage("是否删除" + title + "三方文件夹里的文件")
                                .setNegativeButton("取消", null)
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //删除QQ文件夹 //删除微信文件夹  //删除微信文件夹
                                        String path = BasDataUtil.getSelect3FilePath(selectFile3sGroup.get(groupPosition));
                                        if ("".equals(path)) return;
                                        final File file = new File(path);
                                        if (file.exists()) {
                                            new Thread() {
                                                @Override
                                                public void run() {
                                                    File[] files = file.listFiles();
                                                    for (int i = 0; i < files.length; i++) {
                                                        if (files[i].exists()) {
                                                            files[i].delete();
                                                        }
                                                    }
                                                    Message message = new Message();
                                                    message.what = DE_MSG_DELETE_OK;
                                                    handler.sendMessage(message);
                                                }
                                            }.start();
                                        } else {
                                            Toast.makeText(getContext(), "文件不存在了!", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                }).show();
                    }
                });
            } catch (Exception e) {
                Log.d(BasDataUtil.LOG_TOAST, "解密页面三方文件适配器-父-错误:" + e.toString());
            }
            return convertView;
        }

        @Override
        public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            try {
                ChildViewHolder holder;
                if (convertView == null) {
                    holder = new ChildViewHolder();
                    convertView = LayoutInflater.from(getContext()).inflate(R.layout.file_layout_view, null);
                    holder.tvName = convertView.findViewById(R.id.fileView_tv_fileName);
                    holder.tvMsg = convertView.findViewById(R.id.fileView_tv_msg);
                    holder.layoutVies = convertView.findViewById(R.id.fileVIew_layout_views);
                    holder.img = convertView.findViewById(R.id.fileView_iv_img);
                    convertView.setTag(holder);
                } else {
                    holder = (ChildViewHolder) convertView.getTag();
                }
                final FileViewEntity fileViewEntity = selectFile3sChild.get(selectFile3sGroup.get(groupPosition)).get(childPosition);
                holder.tvName.setText(fileViewEntity.getFileName());
                holder.tvMsg.setText(fileViewEntity.getFileMsg());
                holder.layoutVies.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //实现解密操作
                        setPwdLog(fileViewEntity.getFilePath());
                    }
                });
                if (fileViewEntity.getFileEnd() != null) {
                    int i = getContext().getResources().getIdentifier(getContext().getPackageName() + ":drawable/file_icon_" + FileUtil.getFileNameEedQ(fileViewEntity.getFileEnd()),
                            null, null);
                    if (i == 0)
                        holder.img.setImageResource(R.drawable.file_icon_default);
                    else
                        holder.img.setImageResource(i);
                }
            } catch (Exception e) {
                Log.d(BasDataUtil.LOG_TOAST, "解密页面三方文件适配器-子-错误:" + e.toString());
            }

            return convertView;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return false;
        }

        class GroupViewHolder {
            TextView tvTitle;
            TextView tvDelete;
        }

        class ChildViewHolder {
            TextView tvName;
            TextView tvMsg;
            LinearLayout layoutVies;
            ImageView img;
        }
    }
}
